<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="{{ url_for('static', filename='style_mqtt.css') }}">>
    <link rel="shortcut icon" type="image/vnd.microsoft.icon" href="https://avatar.moonshot.cn/avatar/cmri3mecp7fdvr21ch3g" />
    <title>阿离博客-MQTT 客户端</title>
</head>
<body>
<div class="container" style="margin-bottom: 5px;display: inline-block;">
    <div class="form-group">
        <div>
            <label>主机地址：</label>
            <input id="hostInput" type="text" placeholder="输入Broker主机名" value="broker.emqx.io" style="width: 100%;">
        </div>
        <div>
            <label>端口：</label>
            <input id="portInput" type="text" placeholder="端口" value="8084" style="width: 100%;">
        </div>
    </div>

    <div class="form-group">
        <label>协议类型(选wss,其余未适配)：</label>
        <select id="protocolInput" style="width: 100%;">
            <option value="wss">wss://</option>
            <option value="ws">ws://</option>
            <option value="mqtt">mqtt://</option>
        </select>
    </div>

    <div class="form-group">
        <label>Client ID：</label>
        <input id="clientIdInput" type="text" placeholder="Client ID" value="mqtt_client_webtest_1" style="width: 100%;">
    </div>

    <div class="form-group">
        <label>主题：</label>
        <input id="targetTopicInput" type="text" placeholder="LEDTEST" value="LEDTEST" style="width: 48%;">
	<label> Qos:</label>
        <input id="qosInput" type="number" placeholder="QoS" value="0" style="width: 48%;">
    </div>

    <div class="form-group">
        <button onclick="connect()">连接</button>
        <button onclick="subscribe()">订阅</button>
        <button onclick="disconnect()">断开</button>
        <button onclick="clearMessage()">清空</button>
    </div>

    <div class="form-group">
        <div>
            <label>快捷消息1：</label>
            <input id="quickMessage1" type="text" placeholder="消息1" value="state=1" style="width: 75%;">
            <button onclick="sendQuickMessage('quickMessage1')">发送</button>
        </div>
        <div>
            <label>快捷消息2：</label>
            <input id="quickMessage2" type="text" placeholder="消息2" value="state=0" style="width: 75%;">
            <button onclick="sendQuickMessage('quickMessage2')">发送</button>
        </div>
    </div>

        <div class="form-group">
        <div>
            <label>快捷消息3：</label>
            <input id="quickMessage3" type="text" placeholder="消息3" value="1" style="width: 75%;">
            <button onclick="sendQuickMessage('quickMessage3')">发送</button>
        </div>
        <div>
            <label>快捷消息4：</label>
            <input id="quickMessage4" type="text" placeholder="消息4" value="0" style="width: 75%;">
            <button onclick="sendQuickMessage('quickMessage4')">发送</button>
        </div>
    </div>
    <div class="form-group">
        <div>
            <label>快捷消息5：</label>
            <input id="quickMessage5" type="text" placeholder="消息5" value="on" style="width: 75%;">
            <button onclick="sendQuickMessage('quickMessage5')">发送</button>
        </div>
        <div>
            <label>快捷消息6：</label>
            <input id="quickMessage6" type="text" placeholder="消息6" value="off" style="width: 75%;">
            <button onclick="sendQuickMessage('quickMessage6')">发送</button>
        </div>
    </div>
    <div id="messageDiv"></div>
</div>

<div class="logs" style="margin-top: 10px;">
    <h4>日志窗口</h4>

    <div class="form-group">
        <label>过滤主题：</label>
        <select id="filterTopicInput" style="width: 100%;">
            <option value="所有">所有</option>
        </select>
    </div>
    <div id="logDiv" style="max-height: 200px; overflow-y: auto;"></div>
</div>

<div class="footer" style="margin-top: 10px;">
    <a href="/">返回主页</a>
</div>
<script src="https://cdn.staticfile.net/mqtt/5.3.4/mqtt.min.js" onerror="this.onerror=null;this.src='{{ url_for('static', filename='mqtt.js') }}'"></script>
<script>
    let client;

    function connect() {
        const host = document.getElementById("hostInput").value;
        const port = document.getElementById("portInput").value;
        const clientId = document.getElementById("clientIdInput").value;
        const protocol = document.getElementById("protocolInput").value;

        let url;
        if (protocol === 'mqtt') {
            url = `mqtt://${host}:${port}/mqtt`;
        }
        else if (protocol === 'wss') {
            url = `wss://${host}:${port}/mqtt`;
        }

        else {
            url = `ws://${host}:${port}/mqtt`;
        }

        // 检查是否已经存在一个client实例，如果是，则先断开连接
        if (client && client.connected) {
            client.end();
        }

        // 创建新的client实例
        client = mqtt.connect(url, {clientId: clientId});

        client.on('connect', function () {
            showLog('已连接到MQTT Broker');
        });

        client.on('message', function (topic, message) {
            const filterTopic = document.getElementById("filterTopicInput").value;
            {#const clientID = topic.split('/')[3];  // 假设客户端ID在主题的前部分#}
    if (filterTopic === "所有" || filterTopic === topic) {
        showLog(`时间[${new Date().toLocaleString()}]  收到消息：主题[${topic}] 内容[${message.toString()}] `);
    }
});
    }

    function subscribe() {
        const targetTopic = document.getElementById("targetTopicInput").value;
        client.subscribe(targetTopic, function (err) {
            if (!err) {
                showLog(`时间[${new Date().toLocaleString()}] 成功订阅主题：${targetTopic} `);
                addSubscribedTopicToFilter(targetTopic); // 添加主题到过滤下拉框
            }
        });
    }

    function sendQuickMessage(id) {
        const targetTopic = document.getElementById("targetTopicInput").value;
        const qos = parseInt(document.getElementById("qosInput").value) || 0;
        const message = document.getElementById(id).value;
        client.publish(targetTopic, message, {qos: qos});
        showLog(`时间[${new Date().toLocaleString()}] 发送消息到主题[${targetTopic}] 内容[${message}] QoS[${qos}] `);
    }

    function showLog(message) {
        const logDiv = document.getElementById("logDiv");
        const logEle = document.createElement("div");
        logEle.className = 'log-message';
        logEle.innerText = message;
        logDiv.appendChild(logEle);
        logDiv.scrollTop = logDiv.scrollHeight;
    }

    function clearMessage() {
        const messageDiv = document.getElementById("messageDiv");
        messageDiv.innerHTML = "";
        const logDiv = document.getElementById("logDiv");
        logDiv.innerHTML = "";
    }

    function addSubscribedTopicToFilter(topic) {
        const filterTopicInput = document.getElementById("filterTopicInput");
        const option = document.createElement("option");
        option.value = topic;
        option.text = topic;
        filterTopicInput.appendChild(option);
    }

    function disconnect() {
        if (client) {
            client.end();
            showLog('已断开与MQTT Broker的连接');
        }
    }
</script>
</body>

</html>
